import { AfterContentInit, Component, ContentChild, ElementRef, OnInit, Input, TemplateRef } from '@angular/core';

import { CommonService } from '../../../../core/services/common.service';

@Component({
    selector: 'op-data-grid-column',
    template: `<ng-content></ng-content>`
})
export class DataGridColumnComponent implements AfterContentInit, OnInit {
    @ContentChild(TemplateRef, {static: false}) template: TemplateRef<ElementRef>;
    @Input() title: string;
    @Input() dataField: string;
    @Input() width: string;
    @Input() dataType: string;
    @Input() templateName: string;
    @Input() allowOverflow: boolean = false;
    @Input() allowSorting: boolean;

    constructor(private commonService: CommonService) { }

    ngOnInit(): void { }

    /**
     * Respond after Angular projects external content into the component's view.
     */
    ngAfterContentInit(): void {
        // IMPORTANT!!!
        // If we call initializeProperties in ngOnInit everything looks fine.
        // But once we use ngIf, ngSwitch in the column template it does NOT work.
        // Put it in ngAfterContentInit solve this issue.
        this.initializeProperties();
    }

    /**
     * Initializes the class properties if necessary.
     */
    protected initializeProperties(): void {
        this.allowSorting = this.allowSorting || false;

        // Generates the template name if the customized templated found.
        if (this.template) {
            this.templateName = this.generateTemplateName(this.dataField);
        }
    }

    /**
     * Generates a string name for the data grid template.
     * @param identifier The string of the identifier. The data id value is recommended.
     */
    private generateTemplateName(identifier: string): string {
        return `${identifier}-${this.commonService.getCurrentTimestamp()}-${this.commonService.getRandomNumberWithinRange(1000, 9999)}`;
    }
}